package com.travel.admin.config;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;

public class HttpStreamFilter implements Filter {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
        String contentType = servletRequest.getContentType();
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if ((contentType != null) && (contentType.indexOf(MediaType.MULTIPART_FORM_DATA_VALUE) != -1)) {
            chain.doFilter(request, response);
        } else {
            ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request);
            ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);
            try {
                chain.doFilter(requestWrapper, responseWrapper);
            } finally {
                String requestBody = request.getQueryString();
                if (StringUtils.isEmpty(requestBody)) {
                    requestBody = new String(requestWrapper.getContentAsByteArray());
                }
                logger.info("request url: {}", request.getRequestURL());
                logger.info("request method : {}",request.getMethod());
	            logger.info("request ip : {}",request.getRemoteAddr());
                logger.info("request body : {}", requestBody);
                String responseBody = new String(responseWrapper.getContentAsByteArray());
                logger.info("response body : {}", responseBody);
                responseWrapper.copyBodyToResponse();
            }
        }

	}

	@Override
	public void destroy() {
		
	}

}
